#include "ZTextureAtlas.h"
#include "ZFileUtils.h"

using namespace tinyxml2;

namespace ZuiLib
{

ZTextureAtlasMgr::ZTextureAtlasMgr(ZTextureMgr* mgr)
	:m_textureMgr(mgr)
{
}


ZTextureAtlasMgr::~ZTextureAtlasMgr()
{
}

bool ZTextureAtlasMgr::LoadAtlases(const char* path,tinyxml2::XMLElement *rootElem)
{
	if (rootElem)
	{
		ZString spath = path;
		spath.Append(rootElem->Attribute("imagePath"));
		ZTexturePtr texture = m_textureMgr->GetTextureEx(spath.GetString());
		if (!texture)
			return false;

		XMLElement* elem = rootElem->FirstChildElement("sprite");
		while (elem)
		{
			ZTextureAtlasPtr atlas = new ZRefCountedObject<ZTextureAtlas>();
			atlas->texture = texture;
			atlas->pos.x = elem->IntAttribute("x");
			atlas->pos.y = elem->IntAttribute("y");
			atlas->pos.w = elem->IntAttribute("w");
			atlas->pos.h = elem->IntAttribute("h");

			atlas->offset.x = elem->IntAttribute("oX");
			atlas->offset.y = elem->IntAttribute("oY");

			atlas->size.w = elem->IntAttribute("oW");
			atlas->size.h = elem->IntAttribute("oH");

			m_hashMap.Set(elem->Attribute("n"), atlas);
			elem = elem->NextSiblingElement("sprite");
		}
	}
	return true;
}


bool ZTextureAtlasMgr::LoadAtlases(const char* atlasXml)
{
	XMLDocument xml;
	ZString path = ZFileUtils::GetPathFromName(atlasXml);
	XMLError rslt = xml.LoadFile(path);

	LOG_IF(rslt != XML_SUCCESS) << xml.GetErrorStr1();
	if (rslt == XML_SUCCESS)
	{
		ZString spath;
		int find=path.ReverseFind('/');
		if (find > 0)
			spath = path.Left(find+1);
		else
			spath = path;
		return LoadAtlases(spath,xml.FirstChildElement("TextureAtlas"));
	}
	else
		return false;
}

void ZTextureAtlasMgr::SetAtlas(const char* name, ZTextureAtlasPtr atlas)
{
	m_hashMap.Set(name, atlas);
}


ZTextureAtlasPtr ZTextureAtlasMgr::GetAtlas(const char* name)
{
	return static_cast<ZTextureAtlas*>(m_hashMap.Find(name));
}




}

